<template>
	<view class="">
		<view class="add-box">
			<uni-forms ref="formData" :modelValue="formData" :rules="rules" :label-width="80">
				<uni-forms-item label="日期" name="date" class="add-input">
					<uni-datetime-picker type="date" :clear-icon="false" return-type="timestamp"
						v-model="formData.date" />
				</uni-forms-item>
				<uni-forms-item label="金额" name="count" class="add-input">
					<uni-easyinput class="" type="number" v-model="formData.count" placeholder="请输入金额" />
				</uni-forms-item>
				<uni-forms-item label="类型" name="type" class="add-input">
					<uni-data-checkbox style="margin-top: 5px;" class="add-input-component" v-model="formData.type"
						:localdata="typeOptions"></uni-data-checkbox>
				</uni-forms-item>
				<uni-forms-item label="标签" name="labels" class="add-input">
					<labelsHandler ref="labelsHandler" :initValue="initLabels" @setLabel="setLabel" />
				</uni-forms-item>
				<uni-forms-item label="备注" name="comment" class="add-input">
					<uni-easyinput class="" type="textarea" v-model="formData.comment" placeholder="请输入备注" />
				</uni-forms-item>
				<uni-forms-item label="支付方式" name="payBy" class="add-input">
					<view v-if="payByOptions.length" class="">
						<uni-data-select style="margin-top: 5px;" class="add-input-component" v-model="formData.payBy"
							:localdata="payByOptions"></uni-data-select>
						<!-- <uni-button class="mini-btn" type="" @click="clearValue('payBy')">清除选择</uni-button> -->
					</view>
					<p v-else style="line-height: 36px;color: #999;">请前往“我的”页面创建资产</p>
				</uni-forms-item>
				<uni-forms-item label="关联预算" name="connectBudget" class="add-input">
					<view v-if="budgetOptions.length">
						<uni-data-select style="margin-top: 5px;" class="add-input-component"
							v-model="formData.connectBudget" :localdata="budgetOptions"></uni-data-select>
<!-- 						<uni-button class="mini-btn" type="" @click="clearValue('connectBudget')">清除选择
						</uni-button> -->
					</view>
					<p v-else style="line-height: 36px;color: #999;">请前往“我的”页面创建预算</p>
				</uni-forms-item>
			</uni-forms>
			<div v-if="handleType === 'add'" class="edit-btns">
				<u-button size="small" type="primary" @click="submit">记账</u-button>
				<u-button size="small" type="info " @click="resetFields">重置</u-button>
			</div>
			<div class="edit-btns" v-else>
				<u-button size="small" type="primary" @click="submit" text="修改"></u-button>
				<u-button size="small" type="error" @click="deleteBill" text="删除"></u-button>
			</div>
		</view>
		<!-- <myTabbar/> -->
	</view>
</template>

<script>
	import {
		callCloudFunction
	} from '@/api/requests.js'
	import labelsHandler from './components/labelsHandler.vue'
	import myTabbar from '../../components/myTabbar/myTabbar.vue'
	export default {
		components: {
			labelsHandler
		},
		props: {
			handleType: {
				type: String,
				default: 'add'
			},
			editId: {
				type: String,
				default: ''
			},
		},
		data() {
			return {
				oldData: '',
				userInfo: {},
				initLabels: [],
				formData: {
					_id: '',
					date: 0,
					owner: '',
					count: null,
					type: '',
					labels: [],
					comment: '',
					payBy: '',
					connectBudget: '',
				},
				typeOptions: [{
					"value": 'income',
					"text": "收入"
				}, {
					"value": "expenditure",
					"text": "支出"
				}],
				payByOptions: [],
				budgetOptions: [],
				rules: {
					date: {
						rules: [{
							required: true,
							errorMessage: '请选择日期',
						}, ]
					},
					count: {
						rules: [{
							required: true,
							errorMessage: '请输入金额',
						}, ]
					},
					type: {
						rules: [{
							required: true,
							errorMessage: '请选择类型',
						}, ]
					},
				}
			}
		},
		methods: {
			submit() {
				const that = this
				this.$refs.formData.validate().then(res => {
					if (that.handleType === 'add') {
						that.addBill()
					} else {
						that.editBill()
					}
				}).catch(err => {
					console.log('表单错误信息：', this.formData, err);
				})
			},
			addBill() {
				const that = this
				const data = JSON.parse(JSON.stringify(that.formData))
				if (data.labels.length === 1 && data.labels[0] === "") {
					data.labels = []
				}
				delete data._id
				callCloudFunction('addBill', data, res => {
					uni.showModal({
						content: `添加成功`,
						showCancel: false
					})
					that.updateProperty()
					setTimeout(function() {
						uni.switchTab({
							url: '/pages/statistic/statistic'
						});
					}, 1500);
				}, err => {
					uni.showModal({
						content: `添加失败`,
						showCancel: false
					})
				})
			},
			editBill() {
				const that = this
				callCloudFunction('updateBill', that.formData, res => {
					uni.showModal({
						content: `编辑成功`,
						showCancel: false
					})
					that.updateProperty()
				}, err => {
					uni.showModal({
						content: `编辑失败`,
						showCancel: false
					})
				})
			},
			deleteBill() {
				callCloudFunction('deleteBill', this.formData, res => {
					uni.showModal({
						content: `删除成功`,
						showCancel: false
					})
					uni.navigateBack({
						delta: 1
					});
				}, err => {
					uni.showModal({
						content: `删除失败`,
						showCancel: false
					})
				})
			},
			resetFields() {
				this.formData = {
						_id: '',
						date: this.formData.date || new Date().getTime(),
						owner: this.userInfo._id,
						count: null,
						type: '',
						labels: [],
						comment: '',
						payBy: '',
						connectBudget: '',
					},
					this.initLabels = []
				this.getBudgetsList()
				this.getPropertiesList()
				this.$refs.labelsHandler.init()
			},
			clearValue(key) {
				if (key) {
					this.formData[key] = ''
				}
			},
			updateProperty() {
				const that = this
				const property = that.payByOptions.find(item => {
					return item._id == that.formData.payBy
				})
				property.count = {
					income: Number(property.count) + Number(that.formData.count),
					expenditure: Number(property.count) - Number(that.formData.count),
				} [that.formData.type]
				property.count = Number(property.count.toFixed(2))
				callCloudFunction('updateProperty', property, res => {}, err => {
					uni.showModal({
						content: `资产更新失败，请联系管理员并检查资产`,
						showCancel: false
					})
				})
			},
			getPropertiesList() {
				this.payByOptions = []
				callCloudFunction('getProperties', {
					owner: this.userInfo._id
				}, res => {
					res.result.data.forEach(item => {
						item.text = `${item.propertyName}(${item.count})`
						item.value = item._id
						this.payByOptions.push(item)
					})
				}, err => {
					uni.showModal({
						content: `查询用户资产失败`,
						showCancel: false
					})
				})
			},
			getBudgetsList() {
				this.budgetOptions = []
				callCloudFunction('getBudgets', {
					owner: this.userInfo._id
				}, res => {
					const year = new Date().getFullYear()
					const month = new Date().getMonth() + 1
					const nowMonth = '' + year + '-' + month
					res.result.data.forEach(item => {
						item.text = `${item.budgetName}(${item.value})`
						item.value = item._id
						if(nowMonth == item.month){
							this.budgetOptions.push(item)
						}
					})
				}, err => {
					uni.showModal({
						content: `查询用户预算失败`,
						showCancel: false
					})
				})
			},
			setLabel(labelList) {
				this.formData.labels = labelList
			}
		},
		mounted() {
			const that = this
			if (that.handleType === 'edit') {
				callCloudFunction('getBills', {
					_id: this.editId
				}, res => {
					that.oldData = JSON.stringify(res.result.data[0])
					Object.keys(that.formData).forEach(key => {
						that.formData[key] = res.result.data[0][key]
					})
					that.initLabels = res.result.data[0].labels
				}, err => {
					uni.showModal({
						content: `查询该笔账单失败`,
						showCancel: false
					})
				})
			}
			uni.getStorage({
				key: 'userInfo',
				success: function(res) {
					that.userInfo = res.data
					that.formData.owner = that.userInfo._id
					that.getPropertiesList()
					that.getBudgetsList()
				}
			});
		}
	}
</script>

<style lang="less">
	.add-input {
		margin: 10px;
	}

	.mini-btn {
		width: 60px;
		height: 30px;
		font-size: 12px;
		margin-left: 0;
		margin-top: 4px;
		display: inline-block;
	}

	.add-btn {
		width: 100px;
		height: 40px;
		margin: 0 auto;
		line-height: 40px;
	}

	.edit-btns {
		display: flex;
		justify-content: space-around;
	}

	.edit-btns>.u-button {
		width: 180rpx;
	}

	.add-labels-btn {
		width: 60px;
		height: 30px;
		font-size: 12px;
		margin-left: 0;
		margin-top: 4px;
	}

	.add-box p.others {
		width: 100px;
		margin: 50rpx auto;
	}
</style>
